package cm309.BookingSystem.web.model;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cm309.BookingSystem.common.Common;
import cm309.BookingSystem.web.model.Member;
//"select m FROM Member m where m.memberName= :membername" NOT SQL
@Repository("memberDAO")
public class MemberDAO extends AbstractJpaDAO<Member>  {

    public MemberDAO() {
		super(Member.class);
		
	}

	public Member getMemberByMemberName(String loginName) {
        Query query = this.entityManager
                .createQuery("select m FROM Member m where m.loginName= :loginName");
        query.setParameter("loginName", loginName);
        List members = query.getResultList();
        if (members != null && members.size() == 1) {
        	Common.logger.info("Member isn't null");
            return (Member) members.get(0);
        }
        Common.logger.info("Member is null");
        return null;
    }
	
	public int getNextMemberID() {
		int newMemberID=(Integer)entityManager
				.createQuery("select max(m.memberID) from Member m")
				.getSingleResult()+1;
		Common.logger.info("The new memberID := "+newMemberID);
		return newMemberID;
		
    }
	

	public Member createMember(String memberName,String loginName,String pw
			,int memberAge, String email) {
		Member mb=new Member();
		mb.setMemberID(this.getNextMemberID());
		mb.setMemberName(memberName);
		mb.setLoginName(loginName);
		mb.setPassword(pw);
		mb.setMemberAge(memberAge);
		mb.setEmail(email);
		super.create(mb);
        return mb;
    }
	
}